package com.metadata_system.system.service;


import com.metadata_system.common.db.entity.Database;
import com.metadata_system.common.db.entity.UserOperationLog;
import com.metadata_system.common.db.mapper.DatabaseMapper;
import com.metadata_system.common.db.mapper.UserMapper;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.common.service.UserOperationLogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class DatabaseService {

    @Autowired(required = false)
    protected DatabaseMapper databaseMapper;
    @Autowired(required = false)
    UserMapper userMapper;

    @Autowired
    UserOperationLogService userOperationLogService;

    public ApiResult getList(Integer userId) {
        Example example = new Example(Database.class);
        Example.Criteria criteria = example.createCriteria();

        // 数据库类型: 0.通用数据库 1.项目数据库 2.个人数据库
        criteria.andCondition("(type=0) OR( type=1 AND FIND_IN_SET(" + userId + ",project_user_ids)) OR type=2 AND user_id=" + userId);
        example.setOrderByClause("id desc");

        HashMap<Integer, List<Database>> map = new HashMap<>();
        map.put(0, new ArrayList<>());
        map.put(1, new ArrayList<>());
        map.put(2, new ArrayList<>());
        List<Database> list = databaseMapper.selectByExample(example);
        for (Database database : list) {
            map.get(database.getType()).add(database);
        }
        return ApiResult.success(map);
    }

    /**
     * 创建数据库
     *
     * @param name   数据库名称
     * @param type   数据库类型
     * @param userId 用户id
     * @return 结果
     */
    public ApiResult create(String name, Integer type, Integer userId) {
        if (StringUtils.isBlank(name) || name.length() < 2 || name.length() > 20) {
            return ApiResult.error("数据库名称 长度必须在2-20之间");
        }
        Database database = new Database();
        database.setName(name);
        database.setUserId(userId);
        database.setType(type);
        database.setProjectTotal(0);
        database.setProjectUserIds(userId.toString());
        database.setCreatedTime(new Date());
        database.setUpdatedTime(new Date());
        databaseMapper.insert(database);


        // 记录操作日志
        userOperationLogService.insert(UserOperationLog.builder()
                .userId(database.getUserId())
                .username(this.userMapper.selectByPrimaryKey(database.getUserId()).getUsername())
                .type("Database.Create")
                .content("创建数据库" + database.getName())
                .params(database.getId().toString())
                .createdTime(new Date())
                .build());
        return this.getList(userId);
    }

    /**
     * 更新数据库
     *
     * @param id     数据库id
     * @param name   数据库名称
     * @param userId 用户id
     * @return 结果
     */
    public ApiResult update(Integer id, String name, Integer userId) {
        Database database = databaseMapper.selectByPrimaryKey(id);
        if (database == null) {
            return ApiResult.error("数据库不存在");
        }
        if (StringUtils.isBlank(name) || name.length() < 2 || name.length() > 20) {
            return ApiResult.error("数据库名称 长度必须在2-20之间");
        }
        database.setName(name);
        databaseMapper.updateByPrimaryKeySelective(Database.builder()
                .id(id)
                .updatedTime(new Date())
                .name(name)
                .build());



        // 记录操作日志
        userOperationLogService.insert(UserOperationLog.builder()
                .userId(database.getUserId())
                .username(this.userMapper.selectByPrimaryKey(database.getUserId()).getUsername())
                .type("Database.Update")
                .content("更新数据库" + database.getName())
                .params(database.getId().toString())
                .createdTime(new Date())
                .build());
        return this.getList(userId);
    }

    public void updateDatabaseProjectTotal(Integer id, Integer userId) {
        databaseMapper.updateProjectTotal(id);

        // 记录操作日志
        userOperationLogService.insert(UserOperationLog.builder()
                .userId(userId)
                .username(this.userMapper.selectByPrimaryKey(userId).getUsername())
                .type("Database.Update")
                .content("更新数据库-项目数量")
                .params(id.toString())
                .createdTime(new Date())
                .build());
    }

    public void updateDataTotal(Integer id, Integer userId) {
        databaseMapper.updateDataTotal(id);

        // 记录操作日志
        userOperationLogService.insert(UserOperationLog.builder()
                .userId(userId)
                .username(this.userMapper.selectByPrimaryKey(userId).getUsername())
                .type("Database.Update")
                .content("更新数据库-数据数量")
                .params(id.toString())
                .createdTime(new Date())
                .build());
    }


    /**
     * 删除数据库
     *
     * @param id     数据库id
     * @param userId 用户id
     * @return 结果
     */
    public ApiResult delete(Integer id, Integer userId) {
        Database database = databaseMapper.selectByPrimaryKey(id);
        if (database == null) {
            return ApiResult.error("数据库不存在");
        }
        if (database.getProjectTotal() > 0) {
            return ApiResult.error("数据库下存在项目，不能删除");
        }
        databaseMapper.deleteByPrimaryKey(id);

        // 记录操作日志
        userOperationLogService.insert(UserOperationLog.builder()
                .userId(database.getUserId())
                .username(this.userMapper.selectByPrimaryKey(database.getUserId()).getUsername())
                .type("Database.Delete")
                .content("删除数据库" + database.getName())
                .params(database.getId().toString())
                .createdTime(new Date())
                .build());

        return this.getList(userId);
    }
}
